package cn.seaboot.admin.starter;import cn.seaboot.commons.core.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Mr.css
 * @version 2020-01-16 16:06
 */
@Component
@ServerEndpoint("/socket/{uid}")
public class WebSocketServer {
    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    private static final ConcurrentHashMap<String, WebSocketServer> SERVER_MAP = new ConcurrentHashMap<>();

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String uid, String message) throws IOException {
        if (CommonUtils.isNotEmpty(uid)) {
            logger.info("发送消息到:{}，报文:{}", uid, message);
            SERVER_MAP.get(uid).sendMessage(message);
        } else {
            logger.error("用户 {},不在线！", uid);
        }
    }

    private String uid;
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {
        this.uid = uid;
        this.session = session;
        logger.debug("获取到一个连接：{}", uid);
    }

    @OnClose
    public void onClose(CloseReason closeReason) {
        SERVER_MAP.remove(this.uid);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("用户消息:{},报文:{}", uid, message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误: " + uid, error);
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
